package com.sunfeng.socket.part4;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2021/10/19  11:30
 */
public class TimeServer {
    public void bind(int port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // Netty 用于启动NIO服务端的辅助启动类，目的是降低服务端开发复杂难度
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)  //对应nio 中的ServerSocketChannel
                    .option(ChannelOption.SO_BACKLOG, 1024) // 设置线程队列等待链接的个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChildChannelHandler());
            //绑定端口    这个操作是异步的类似与Java的Future 主要用于异步操作的通知回调
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            //等待服务器监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅的退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {

            ChannelPipeline pipeline = ch.pipeline();
               pipeline.addLast(new LineBasedFrameDecoder(1024));
           pipeline.addLast(new StringDecoder());
            pipeline.addLast(new TimeServerHandler());

        }
    }

    public static void main(String[] args) throws InterruptedException {
        new com.sunfeng.netty.atguigu.linebasedframedecoder.TimeServer().bind(8888);
        System.out.println("启动成功");
    }
}
